angular.module('tic-tac-toe', []);

function TicTacToeController($scope) {
	var controller = this;
	
	$scope.players = [ 'X', '0' ];
	
	$scope.resetBoard = function(){
		$scope.board = controller.createBoard(boardSize);
		$scope.currentPlayerIndex = 0;
		$scope.winner = null;
	};
	
	$scope.resetBoard();

	$scope.placeSymbol = function(row, column) {
		if ($scope.winner || $scope.board[row][column].content)
			return;
		
		$scope.board[row][column].content = $scope.players[$scope.currentPlayerIndex];
		if ($scope.currentPlayerIsVictorious()) {
			alert("victory");
			$scope.winner = $scope.players[$scope.currentPlayerIndex];
		} else {
			$scope.nextPlayer();
		}
	};

	$scope.nextPlayer = function() {
		if (this.currentPlayerIndex == 0)
			this.currentPlayerIndex = 1;
		else
			this.currentPlayerIndex = 0;
	};

	$scope.currentPlayerIsVictorious = function() {
		var board = $scope.board;
		
		function row(row) {
			return same(board[row][0], board[row][1], board[row][2]);
		}
		function col(col) {
			return same(board[0][col], board[1][col], board[2][col]);
		}
		function diagonal(i) {
			return same(board[0][1 - i], board[1][1], board[2][1 + i]);
		}
		function same(a, b, c) {
			return a.content && (a.content == b.content && b.content == c.content) ;
		}
		
		return row(0) || row(1) || row(2) || col(0) || col(1) || col(2) || diagonal(-1) || diagonal(1);
	};

}

TicTacToeController.prototype.createBoard = function(length) {
	var board = [];

	for ( var i = 0; i < length; i++) {
		var row = [];
		for ( var j = 0; j < length; j++) {
			row.push({});
		}
		board.push(row);
	}

	return board;
};